#include <stddef.h>
#include <stdlib.h>
#include "worker.h"

struct tag_worker {
    pthread_t tid;
    void *context;
    void (*start_routine)(void *);
};

static void *wrapped_thread_routine(void *worker_ctx)
{
    worker_t *worker;
    if (worker_ctx == NULL) {
        pthread_exit(NULL);
    }
    worker = (worker_t *)worker_ctx;
    if (worker->start_routine == NULL) {
        pthread_exit(NULL);
    }
    worker->start_routine(worker->context);
    pthread_exit(NULL);
}


worker_t *worker_create(void *context, void (*start_routine)(void *))
{
    int ret;
    pthread_t tid;
    worker_t *worker;

    worker = (worker_t *)malloc(sizeof(worker_t));
    if (worker == NULL) {
        return NULL;
    }
    worker->context = context;
    worker->start_routine = start_routine;

    ret = pthread_create(&tid, NULL, wrapped_thread_routine, (void *)worker);
    if (ret != 0) {
        free(worker);
        return NULL;
    }
    pthread_detach(tid);
    worker->tid = tid;
    return worker;
}


void worker_destroy(worker_t *worker)
{
    if (worker == NULL) {
        return;
    }
    free(worker);
    return;
}
